<template>
  <!-- 工会组织-树下拉框查询 -->
  <a-tree-select
    v-bind="$attrs"
    v-on="listeners"
    v-model="currentValue"
    :tree-data="treeData"
    allowClear
    showSearch
    treeDefaultExpandAll
    :maxTagCount="maxTagCount"
    :filterTreeNode="fillter"
    :replaceFields="{ children: 'children', title: 'unionOrgName', key: 'id', value: 'id' }"
    :show-checked-strategy="SHOW_CHILD"
    :placeholder="placeholder"
  >
    <a-icon v-if="fetching" style="color: #096dd9" slot="suffixIcon" type="loading" />
  </a-tree-select>
</template>
<script>
import { getUnionTreeList ,queryTreeListByNoAuth} from '@/api/union/organizationManagement' // api
import { TreeSelect } from 'ant-design-vue'
const SHOW_CHILD = TreeSelect.SHOW_CHILD

export default {
  name: 'SelectTreeUnion',
  data() {
    return {
      fetching: false,
      treeData: [],
      dataList: [],
      SHOW_CHILD,
    }
  },
  props: {
    // v-model绑定的数据
    value: {
      type: [Array, String, Object],
    },
    // placeholder
    placeholder: {
      type: String,
      default: () => '请选择工会组织',
    },
    // 多选状态下,最大显示选项数
    maxTagCount: {
      type: Number,
      default: () => 2,
    },
      isAuth: {
          type: Boolean,
          default:true
      }
  },
  computed: {
    /**
     * 重构事件（取消search事件）
     */
    listeners(){
      let listeners = this.$listeners
      delete listeners.search
      return listeners
    },
    // 转换绑定的选中数据，与v-model同步
    currentValue: {
      get: function () {
        if (this.value && this.dataList.length > 0) {
          let option = this.dataList.find((item) => item.id === this.value)
          this.$emit('update:option', option)
          this.$emit('getOption', option)
        }
        return this.value
      },
      set: function (value) {
        this.$emit('input', value)
      },
    },
  },
  methods: {
    /**
     * 筛选节点
     */
    fillter(searchVal, treeNode) {
      return treeNode?.data?.props?.unionOrgName?.includes(searchVal)
    },
    /**
     * 遍历树
     */
    getData(data) {
      for (let i = 0; i < data.length; i++) {
        let node = data[i] // 节点
        this.dataList.push(node)
        if (node.children?.length > 0) {
          this.getData(node.children)
        }
      }
    },
    /**
     * 获取树
     */
    getList() {
      // 获取下拉框列表
      let args = {}
      this.fetching = true
        let api = queryTreeListByNoAuth
        if (this.isAuth){
            api = getUnionTreeList
        }
        api(args)
        .then((res) => {
          this.fetching = false
          if (res.code === '0') {
            this.getData(res.data)
            this.treeData = res.data
          }
        })
        .catch(() => {
          this.fetching = false
        })
    },
  },
  mounted() {
      this.getList()
  },
}
</script>
